package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.*;
import com.itheima.commons.BaseContext;
import com.itheima.dao.OrdersDao;
import com.itheima.dto.OrdersDto;
import com.itheima.dto.SetmealDto;
import com.itheima.exception.CustomException;
import com.itheima.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author Tang
 * @date 2023/1/12
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 下单操作
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //0.开启事务
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("该用户不存在！");
        }
        //使用工具类生成id
        long orderId = IdWorker.getId();

        //1.保存订单明细数据到order_detail表中
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //2.构造orderDetail订单明细数据：
        LambdaQueryWrapper<ShoppingCart> cartQueryWrapper = new LambdaQueryWrapper<>();
        cartQueryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> cartList = shoppingCartService.list(cartQueryWrapper);
        if (cartList.isEmpty()) {
            throw new CustomException("请先添加商品到购物车！");
        }
        //订单总金额
        BigDecimal sumAmount = new BigDecimal(0);
        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            //2.1 将购物车数据信息直接拷贝到订单明细对象中
            BeanUtils.copyProperties(cart, orderDetail);
            //2.2 设置订单id
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
            //2.3 订单金额计算加总
            sumAmount = sumAmount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }
        //2.4 订单明细数据保存到order_detail表中
        orderDetailService.saveBatch(orderDetailList);

        //3.保存订单信息数据到orders表中
        //4.需要补齐一些字段
        orders.setId(orderId);  //主键id
        orders.setNumber(UUID.randomUUID().toString());  //编号
        orders.setStatus(2);     //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(sumAmount);     //订单总金额
        orders.setUserName(user.getName());

        //5. 根据地址id查询地址表
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("请先添加收货地址！");
        }
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        +(addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        +(addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        +(addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //5.保存订单数据到orders表中
        this.save(orders);

        //6.清空购物车
        shoppingCartService.remove(cartQueryWrapper);
    }

    @Override
    public Page<OrdersDto> findPage(Integer page, Integer pageSize) {
        //1.new Page<SetmealDto>创建分页对象，records、total、size....
        Page<OrdersDto> ordersDtoPage = new Page<>();

        //2.封装 Page<OrdersDto>数据：
        //2.1 构造分页对象 Page<Setmeal>(page, pageSize)
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //2.2 构造查询对象，可以根据套餐名称进行分页查询
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        Long userId = BaseContext.getCurrentId();
        queryWrapper.like(Orders::getUserId,userId);

        //2.3 调用自身的page方法，传入分页对象以及查询对象，最终得到Page<Setmeal>对象数据，里面records（List<Setmeal>）、total、size....
        this.page(ordersPage, queryWrapper);

        //2.4 Page<Setmeal>所有属性拷贝到Page<SetmealDto>，排除records属性
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");

        //2.5 封装Page<SetmealDto>的records属性：List<SetmealDto>
        List<OrdersDto> ordersDtoList = new ArrayList<>();
        List<Orders> ordersList = ordersPage.getRecords();
        //a.循环遍历List<Setmeal>
        for (Orders orders : ordersList) {
            //b.构造SetmealDto对象数据，设置setmeal属性
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            //c.获取categoryName属性（根据分类id查询分类表）封装到SetmealDto
            List<OrderDetail> list = orderDetailService.list();
            ordersDto.setOrderDetails(list);
            //d.将SetmealDto对象添加到List<SetmealDto>
            ordersDtoList.add(ordersDto);
        }
        //2.6 设置Page<SetmealDto>对象的records属性：List<SetmealDto>
        ordersDtoPage.setRecords(ordersDtoList);

        //3.返回Page<SetmealDto>
        return ordersDtoPage;
    }
}
